package com.ljx.funchat.chat.dao;

import com.ljx.funchat.chat.domain.entity.Message;
import com.ljx.funchat.chat.domain.enums.MessageStatusEnum;
import com.ljx.funchat.chat.domain.vo.req.ChatMessagePageReq;
import com.ljx.funchat.chat.domain.vo.req.ChatMessageReq;
import com.ljx.funchat.chat.mapper.MessageMapper;
import com.ljx.funchat.chat.service.IMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.funchat.common.domain.vo.resp.CursorPageBaseResp;
import com.ljx.funchat.common.utils.CursorUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiJunXi
 * @since 2024-02-14
 */
@Service
public class MessageDao extends ServiceImpl<MessageMapper, Message>{

    public Integer getUnReadCount(Long roomId, Date readTime) {
        return lambdaQuery()
                .eq(Message::getRoomId, roomId)
                .gt(Objects.nonNull(readTime), Message::getCreateTime, readTime)
                .count();
    }

    public CursorPageBaseResp<Message> getMessagePage(Long uid, ChatMessagePageReq req) {
        return CursorUtils.getCursorPageByMysql(this, req, wrapper -> {
            wrapper.eq(Message::getRoomId, req.getRoomId());
            wrapper.eq(Message::getStatus, MessageStatusEnum.NORMAL.getStatus());
        }, Message::getId);
    }

    public void updateRedbagInvalidById(Long messageId) {
        Message message = this.baseMapper.selectById(messageId);
        message.getExtra().getRedBagMsgDTO().setValid(false);
        this.baseMapper.updateById(message);
    }
}
